package com.hxtec.polaris.commons.thread;

import com.hxtec.polaris.entity.ShopCategory;
import com.hxtec.polaris.mapper.ShopCategoryMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Describtion 构建分类路径
 * @Author yonyong
 * @Date 2019/11/15 17:02
 * @Version 1.0.0
 **/
public class BuildPathRunable implements Runnable{
    private final  static Long TIME_STAMP = 30000L;
    private final static Logger logger = LoggerFactory.getLogger(BuildPathRunable.class);
    private ServletContext context = null;
    private final CountDownLatch doneSignal;
    private ShopCategoryMapper shopCategoryMapper;

    public BuildPathRunable(ServletContext context,CountDownLatch doneSignal){
        this.context = context;
        this.doneSignal = doneSignal;
    }
    @Override
    public void run() {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        ShopCategoryMapper shopCategoryMapper = webApplicationContext.getBean(ShopCategoryMapper.class);
        this.shopCategoryMapper = shopCategoryMapper;
        try{
            synchronized (doneSignal){
                doneSignal.countDown();
                callBuildPath();
                logger.info("********分类路径构建成功**********");
            }
            doneSignal.await();
        }catch (Exception e){
            logger.error("*****发生异常*******,当前指针"+doneSignal);
            e.printStackTrace();
        }
    }


    /**
     * 构建分类路径
     */
    public void callBuildPath(){
        List<ShopCategory> list = shopCategoryMapper.getAllCategory();
        for (ShopCategory shopCategory:list){
            //获取构建的类别路径
            StringBuilder path = new StringBuilder("-");
            path.append(shopCategory.getId());
            getPath(shopCategory,path,new Date());
            path.append("-");
            shopCategory.setComment1(String.valueOf(path));
            int count = shopCategoryMapper.selectChildCountById(shopCategory.getId());
            if(count>0){
                shopCategoryMapper.updateCategoryPath(String.valueOf(shopCategory.getId()),String.valueOf(path),"Y");
            }else if(count == 0){
                shopCategoryMapper.updateCategoryPath(String.valueOf(shopCategory.getId()),String.valueOf(path),"N");
            }
        }
    }

    /**
     * 获取某个分类的路径
     * @param shopCategory
     * @param path
     * @return
     */
    private StringBuilder getPath(ShopCategory shopCategory, StringBuilder path, Date date){
        if (System.currentTimeMillis()-date.getTime() > TIME_STAMP){
            logger.error("*****操作时间过长，可能陷入死循环*******,当前指针"+doneSignal);
            return null;
        }
        if (StringUtils.isNotBlank(shopCategory.getParentId())){
            List<ShopCategory> list= shopCategoryMapper.getCategoryById(shopCategory.getParentId());
            if (null != list && list.size()>0){
                ShopCategory shopCategory1 = list.get(0);
                path.append("-").append(shopCategory1.getId());

                if (StringUtils.isNotBlank(shopCategory1.getParentId())){
                    getPath(shopCategory1,path,date);
                }
            }
        }
        return path;
    }
}
